# import re
#
# def convert_markdown_headings(md_content, base_prefix):
#     """
#     自动根据 base_prefix 为 Markdown 添加递增标题编号。
#     支持最多 5 层标题，保留内容与结构不变。
#
#     :param md_content: Markdown 文本内容
#     :param base_prefix: 起始编号前缀，如 "3.1.1"
#     :return: 添加编号后的 Markdown 内容
#     """
#     # 初始化编号结构：基础前缀+最多5层补齐
#     prefix_base = list(map(int, base_prefix.strip().split('.')))
#     base_depth = len(prefix_base)
#     counters = prefix_base + [0] * (100 - base_depth)
#     lines = md_content.splitlines()
#     output_lines = []
#     for line in lines:
#         match = re.match(r'^(#{1,100})\s+(.*)', line.strip())
#         if match:
#             level = len(match.group(1))
#             content = match.group(2).strip()
#             index = base_depth - 1 + level - 1  # 计算要递增的索引位置
#             counters[index] += 1  # 当前层级递增
#             for i in range(index + 1, len(counters)):  # 更深层清零
#                 counters[i] = 0
#             prefix = '.'.join(str(num) for num in counters[:index + 1])
#             output_lines.append(f"{prefix} {content}")
#         else:
#             output_lines.append(line)
#     return '\n'.join(output_lines)
#
# # 示例使用
# if __name__ == "__main__":
#     with open("D:\\hbyt\\AI智能投标\\能力组件-附件\\测试1.md", "r", encoding="utf-8") as f:
#         content = f.read()
#     result = convert_markdown_headings(content, base_prefix="3.1")
#     print("result",result)
#     with open("测试1.md", "w", encoding="utf-8") as f:
#         f.write(result)
#     print("✅ 编号处理完成，结果已保存。")
import re

def convert_markdown_headings(md_content, base_prefix):
    """
    自动根据 base_prefix 为 Markdown 添加递增标题编号。
    起始编号如 base_prefix=3.1，则从 3.1.1 开始。
    """
    prefix_base = list(map(int, base_prefix.strip().split('.'))) + [0]  # ✅ 补 0 保证从 .1 开始
    base_depth = len(prefix_base)
    counters = prefix_base + [0] * (100 - base_depth)

    lines = md_content.splitlines()
    output_lines = []

    for line in lines:
        match = re.match(r'^(#{1,100})\s+(.*)', line.strip())
        if match:
            level = len(match.group(1))
            content = match.group(2).strip()
            index = base_depth + level - 2  # 层级偏移
            counters[index] += 1
            for i in range(index + 1, len(counters)):
                counters[i] = 0
            prefix = '.'.join(str(num) for num in counters[:index + 1])
            output_lines.append(f"{prefix} {content}")
        else:
            output_lines.append(line)

    return '\n'.join(output_lines)

# 示例使用
if __name__ == "__main__":
    with open("D:\\hbyt\\AI智能投标\\能力组件-附件\\测试1.md", "r", encoding="utf-8") as f:
        content = f.read()

    result = convert_markdown_headings(content, base_prefix="1")

    with open("测试1.md", "w", encoding="utf-8") as f:
        f.write(result)

    print("✅ 编号处理完成，结果已保存。")

